import ErrorCode from "../script/ErrorCode";
import { saveToLocal, removeLocal, loginToNative } from "../script/fn";
import { Toast } from "vant";
export const commonLogin = {
  created() {},
  methods: {
    //自动登录
    autoLogin() {
      this.auto = !this.auto;
      if (this.auto) {
        this.rember = 1;
      }
    },
    remember() {
      this.rember = !this.rember;
    },
    //清空表单
    empty() {
      this.send.phoneNumber = "";
      this.send.password = "";
    },
    //根据input输入内容判断禁用登录按钮
    disable() {
      const valid_phone = this.$validate.notEmpty.regex.test(
        this.send.phoneNumber
      );
      const valid_password = this.$validate.password.regex.test(
        this.send.password
      );
      if (this.show == 1) {
        if (valid_phone && valid_password) {
          this.$emit("toggHeight", true);
        } else {
          this.$emit("toggHeight", false);
        }
      }
    },
    //格式化数据
    formatData(arr) {
      let zbInfos = [];
      arr.map(item => {
        let zbInfo = {};
        zbInfo["zbId"] = item.targetId || "";
        zbInfo["zbKey"] = item.clientTarget.keywords || "";
        zbInfo["zbName"] = item.clientTarget.targetName || "";
        zbInfo["zbExpireFlag"] = item.clientTarget.targetModel || 0;
        zbInfo["zbCreateTime"] = String(item.createTime) || "";
        zbInfo["zbEndTime"] = String(item.endTime) || "";
        zbInfo["zbIsExpire"] = item.isEnd || 0;
        zbInfo["zbAvailableTimes"] = item.clientTarget.stockNum || 0;
        zbInfo["zbUsedTimes"] = item.clientTarget.useStockNum || 0;
        zbInfo["stock"] = [];
        if (
          item.clientTarget.targetRecords != undefined &&
          item.clientTarget.targetRecords.length > 0
        ) {
          item.clientTarget.targetRecords.map(i => {
            let stocks = {};
            stocks["code"] = Number(i.code) || 0;
            stocks["stockCode"] = i.stockCode || "";
            zbInfo["stock"].push(stocks);
          });
        }
        zbInfos.push(zbInfo);
      });
      return zbInfos;
    },
    //登录
    submit() {
      const self = this;
      if (!this.$validate.phone.regex.test(this.send.phoneNumber)) {
        return this.$emit("showError", this.$validate.phone.error);
      }
      if (!this.$validate.notEmpty.regex.test(this.send.password)) {
        return this.$emit("showError", this.$validate.notEmpty.error);
      }
      if (!this.$validate.password.regex.test(this.send.password)) {
        return this.$emit("showError", this.$validate.password.error);
      }
      const { version } = this.$fn.getUrlParams();
      if (!navigator.onLine) return Toast("网络连接失败，请检查网络设置");
      this.$store
        .dispatch("passwordLogin", {
          phoneNumber: this.send.phoneNumber,
          password: this.send.password,
          loginVersion: !version || version == 1 ? 2 : version //2为标准版
        })
        .then(function({ data, status }) {
          self.$emit("goBuy", false);
          if (status != 1) {
            if (status == 400001) {
              self.$emit("goBuy", true);
            } else {
              self.$emit("showError", ErrorCode[status]);
            }
          }
          if (version >= 3) {
            saveToLocal(
              {
                userId: data.userId,
                productId: data.order.productId,
                endTime: data.order.endTime
              } //订单结束时间
            );
          }
          saveToLocal({ remember: +self.rember, autoLogin: +self.auto });

          if (self.rember) {
            saveToLocal({
              phoneNumber: self.send.phoneNumber,
              password: self.send.password
            });
          } else {
            removeLocal(["phoneNumber", "password"]);
          }
          self.findUserTarget();
          self.$store.dispatch("findUserTarget").then(back => {
            if (!back) {
              window.prompt(
                "",
                `up://["web_user_login",${Date.now()},{"type":"login","data":{"token":"${
                  window.userInfo.centralToken
                }","time":"${window.systemTime}","logintype":"0","openid":"${
                  window.userInfo.phone
                }","indexcollection":0,"expiretime":"${
                  data.order ? data.order.endTime : ""
                }","productid":"${
                  data.order ? data.order.productId : ""
                }","isInside":${window.userInfo.isInside},"zbInfo":[]}}]`
              );
            } else {
              window.prompt(
                "",
                `up://["web_user_login",${Date.now()},{"type":"login","data":{"token":"${
                  window.userInfo.centralToken
                }","time":"${window.systemTime}","logintype":"0","openid":"${
                  window.userInfo.phone
                }","indexcollection":1,"expiretime":"${
                  data.order ? data.order.endTime : ""
                }","productid":"${
                  data.order ? data.order.productId : ""
                }","isInside":${
                  window.userInfo.isInside
                },"zbInfo":${JSON.stringify(self.formatData(back))}}}]`
              );
            }
          });
        });
    },
    findUserTarget() {}
  }
};
